package com.lyl.security.common.sercurity.handler;

import com.lyl.security.common.result.ErrorCode;
import com.lyl.security.common.result.Result;
import com.lyl.security.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class AuthFailureHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.error("自定义认证异常", authException);
        ServletUtils.write(response, Result.build(ErrorCode.UNAUTHORIZED).setMsg(authException.getMessage()));
    }
}
